#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <vector>

const int num = 5;// 创建5个线程
int tickets = 10000;// 1W张票


class customer
{
public:
    customer(const std::string& name, pthread_t& tid):_name(name), _tid(tid) {}
    
    pthread_t getTid()
    {
        return _tid;
    }

    std::string getName()
    {
        return _name;
    }

private:
    std::string _name;// 线程的名字
    pthread_t _tid;// 线程的tid
};

pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;// 定义一把全局的互斥锁

void* route(void* args)
{
    customer* cum = static_cast<customer*>(args);
    while (true)
    {
        //对访问共享资源的前后加锁
        pthread_mutex_lock(&g_mutex);
        // 临界区
        if(tickets > 0)
        {
            usleep(1000);// 模拟抢票
            std::cout << cum->getName() << ", 抢到了第" << tickets << "票" << std::endl;
            tickets--;
            // 临界区
            pthread_mutex_unlock(&g_mutex);// 当访问结束了就解锁
        }
        else
        {
            pthread_mutex_unlock(&g_mutex);// 当访不符合条件就解锁
            break;
        }
    }

    return nullptr;
}


int main()
{
    std::vector<customer*> tids;// 管理线程
    for(int i = 0; i < num; i++)     
    {
        std::string name = "thread_" +std::to_string(i+1);
        pthread_t tid;
        customer* cum = new customer(name, tid);
        pthread_create(&tid, nullptr, route, (void*)cum);
        tids.emplace_back(cum);
    }

    for(auto& cum : tids)
    {
        pthread_join(cum->getTid(), nullptr);
    }

    return 0;
}



